﻿package  {
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.display.Sprite;
	import flash.display.Shape;

	public class SpacePuzzle extends Sprite {
		private var cellArr:Array = [0xffffff, 0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, 0xf0f0f0, 0x0f0f0f, 0x000000];
		private var zSum:Number;
		
		private var answerX:Number;
		private var answerY:Number;
		
		private var spaceSp:Sprite = new Sprite();
		
		public function SpacePuzzle() {
			init();
		}
		
		private function init(){
			spaceSp = new Sprite();
			
			answerX = Math.random() * 500 + 25;
			answerY = Math.random() * 150 + 25;
			
			zSum = 0;
			for(var i:int = 0; i < cellArr.length; i ++){
				var cell:Shape = new Shape();//Cell();
				cell.graphics.beginFill(cellArr[i]);
				cell.graphics.drawRect(-10, -10, 20, 20);
				cell.graphics.endFill();
				
				spaceSp.addChild(cell);
				
				cell.x = 0;
				cell.y = 100 + i * 20;
				cell.z = int(Math.random() * (cellArr.length + 10)) * 10;
				zSum += cell.z;
			}
			this.addChild(spaceSp);
			spaceSp.x = answerX;
			spaceSp.y = answerY;
			
			zSum /= cellArr.length;
			for(var j:int = 0; j < cellArr.length; j ++){
				cell = spaceSp.getChildAt(j) as Shape;
				cell.scaleX = cell.scaleY += (cell.z - zSum) / 1000;
			}
			
			stage.addEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
		}
		
		private function moveHandler(e:MouseEvent){
			spaceSp.rotationY = answerX - mouseX;
			spaceSp.rotationX = answerY - mouseY;
			
			if(Math.abs(mouseX - answerX) < 10 && Math.abs(mouseY - answerY) < 10){
				trace("bingo");
				stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveHandler);
				this.removeChild(spaceSp);
				
				init();
			}
		}
	}
	
}
